//
//  DataAccess.m
//  protesteya
//
//  Created by Sebastian Bene on 11/3/13.
//  Copyright (c) 2013 Obligatorio Dispositivos Moviles. All rights reserved.
//

#import "DataAccess.h"

@implementation DataAccess

@synthesize model;
@synthesize coordinator;
@synthesize context;

-(id)init
{
    self = [super init];
    
    if (self)
    {
        model = [NSManagedObjectModel mergedModelFromBundles:nil];
        coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [paths objectAtIndex:0];
        NSString *filePath = [documentsDir stringByAppendingPathComponent:@"datastore.sqllite"];
        NSURL *databaseUrl = [NSURL fileURLWithPath:filePath];
        
        NSError *error = nil;
        [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:databaseUrl options:nil error:&error];
        
        context = [[NSManagedObjectContext alloc] init];
        [context setPersistentStoreCoordinator:coordinator];
        
    }
    return self;
}

-(void) SetTweetFavorite:(NSString *)tweetId favorite:(BOOL)favorite
{
    Tweet *tweet = [self GetTweet:tweetId];
    
    if(tweet == nil)
    {
        tweet = [NSEntityDescription insertNewObjectForEntityForName:@"Tweet" inManagedObjectContext:context];
        tweet.retweeted = [NSNumber numberWithBool:NO];
    }
    
    
    tweet.tweetId = tweetId;
    tweet.favorite = [NSNumber numberWithBool:favorite];
    
    NSError *error = nil;
    [context save:&error];
}

-(void) SetTweetRetweeted:(NSString *)tweetId retweeted:(BOOL)retweeted
{
    Tweet *tweet = [self GetTweet:tweetId];
    
    if(tweet == nil)
    {
        tweet = [NSEntityDescription insertNewObjectForEntityForName:@"Tweet" inManagedObjectContext:context];
        tweet.favorite = [NSNumber numberWithBool:NO];
    }
    
    tweet.tweetId = tweetId;
    tweet.retweeted = [NSNumber numberWithBool:retweeted];
    
    NSError *error = nil;
    [context save:&error];
}

-(Tweet *) GetTweet:(NSString *)tweetId
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *desc = [NSEntityDescription entityForName:@"Tweet" inManagedObjectContext:context];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"tweetId = %@", tweetId];
    
    [fetchRequest setPredicate:predicate];
    [fetchRequest setEntity:desc];
    
    NSError *error = nil;
    NSArray *tweets = [context executeFetchRequest:fetchRequest error:&error];
    
    return (error == nil && tweets.count > 0) ? tweets[0] : nil;
}

@end
